<template>
  <div class="log-manage-info">
    <div class="m-t-10px"></div>
    <!-- 当前日志等级 -->
    <div class="current-log-level m-b-20px">
      <span>当前AP日志等级 ：</span>
      <span class="log-level-text">{{ currentLogLevel }}</span>
    </div>
    <!-- 当pageType为7时，显示分屏日志 -->
    <div v-if="props.pageType === 7" class="split-log-wrapper">
      <!-- <div class="m-b-10px flex gap-10px items-center">
        <span >输入过滤值</span>
        <el-input style="width: 200px;" v-model="filterValue" placeholder="输入过滤值"></el-input>
        <div class="global_btn" @click="handleFilter">过滤</div>
      </div> -->
      <div class="split-log-container">
        <!-- 左侧未过滤日志 -->
        <div class="log-panel unfiltered-logs">
          <div class="panel-title">CP网络日志</div>
          <div class="log_container" ref="unfilteredContainerRef" @scroll="onUnfilteredScroll">
            <div class="virtual-list" :style="{ height: unfilteredTotalHeight + 'px' }">
              <div class="virtual-list-phantom" :style="{ transform: `translateY(${unfilteredOffsetY}px)` }">
                <div v-for="item in unfilteredVisibleData" :key="item.index" class="log-item">
                  <span class="log-index">[{{ item.index + 1 }}]</span>
                  <span class="log-content">{{ item.content }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧过滤后日志 -->
        <div class="log-panel filtered-logs">
          <div class="panel-title">入网日志<span class="filter-count" v-if="cpFilterConfig.filterList.length > 0">({{
              cpFilterConfig.filterList.length }})</span></div>
          <div class="log_container" ref="filteredContainerRef" @scroll="onFilteredScroll">
            <div class="virtual-list" :style="{ height: filteredTotalHeight + 'px' }">
              <div class="virtual-list-phantom" :style="{ transform: `translateY(${filteredOffsetY}px)` }">
                <div v-for="item in filteredVisibleData" :key="item.index" class="log-item">
                  <span class="log-index">[{{ item.index + 1 }}]</span>
                  <span class="log-content">{{ item.content }}</span>
                </div>
              </div>
            </div>
            <div class="no-results" v-if="cpFilterConfig.filterList.length === 0">
              没有找到匹配的结果
            </div>
          </div>
        </div>
      </div>

      <!-- 底部按钮容器 -->
      <div class="scroll-buttons-container">
        <!-- 左侧滚动按钮 -->
        <transition name="fade">
          <div class="global_btn unfiltered-scroll-btn" :icon="ArrowDown"
            v-if="!isUnfilteredAtBottom && cpFilterConfig.unFilterList.length > 0"
            @click="scrollUnfilteredToBottomManually">
            <span>{{ t('functionService.scroll_to_bottom_label') }}</span>
            <el-icon><ArrowDown /></el-icon>
          </div>
        </transition>

        <!-- 右侧滚动按钮 -->
        <transition name="fade">
          <div class="global_btn filtered-scroll-btn" :icon="ArrowDown"
            v-if="!isFilteredAtBottom && cpFilterConfig.filterList.length > 0" @click="scrollFilteredToBottomManually">
            <span>{{ t('functionService.scroll_to_bottom_label') }}</span>
            <el-icon><ArrowDown /></el-icon>
          </div>
        </transition>
      </div>
    </div>
    <!-- 当pageType不为7时，显示正常日志 -->
    <div v-if="props.pageType !== 7" class="log_container" ref="containerRef" @scroll="onScroll"
      style="padding-bottom: 50px;">
      <div class="virtual-list" :style="{ height: totalHeight + 'px' }">
        <div class="virtual-list-phantom" :style="{ transform: `translateY(${offsetY}px)` }">
          <div v-for="item in visibleData" :key="item.index" class="log-item">
            <span class="log-index">[{{ item.index + 1 }}]</span>
            <span class="log-content">{{ item.content }}</span>
          </div>
        </div>
      </div>
    </div>
    <!-- 控制面板（始终显示） -->
    <div class="control-panel">
      <div class="m-t-10px">
        <div class="flex gap-20px">
          <div class="flex gap-20px w-50%">
            <div class="global_btn" v-globalLoading="handleDownloadLog">
              {{ logTypeLabel }}
            </div>
            <div class="global_btn" @click="() => handlePauseDownload('export')"
              v-if="downloadConfig.export.isDownloading">
              {{ t('functionService.pause_download_label') }}
            </div>        
            <div class="global_btn"  v-if="props.pageType !== 7" @click="handleCurrentExportLog">
            导出当前日志
            </div>
            <div class="global_btn"  v-if="props.pageType !== 7&&props.pageType ==4" @click="showLogLevelSettingDialog">
             日志等级设置
            </div>
            <div class="flex gap-20px"  v-if="props.pageType === 7">
              <div class="global_btn" v-globalLoading="handleExportCpLog.bind(null, 'unfiltered')">
              导出当前CP网络日志
            </div>
            <div class="global_btn" @click="clearCplog('unfiltered')">
              <el-icon :size="16" class="m-l-5px">
                <Delete />
              </el-icon>
              清除当前CP网络日志
            </div>
            </div>
            <div class="global_btn" @click="handleClearLog">
            <el-icon :size="16" class="m-l-5px">
              <Delete />
            </el-icon>
            {{ t('functionService.clear_log_label') }}
           </div>
          </div>
          <!-- 入网日志处理 -->
          <div class="flex gap-20px w-50%"  v-if="props.pageType === 7">         
            <div class="global_btn" v-globalLoading="handleExportCpLog.bind(null, 'filtered')">
              导出当前CP入网日志
            </div>
            <!-- 清除当前CP入网日志 -->
            <div class="global_btn" @click="clearCplog('filtered')">
              清除当前CP入网日志
            </div>
          </div>    
        </div>
        <div class="global_btn float-right" :icon="ArrowDown"
          v-if="!isAtBottom && logList.length > 0 && props.pageType !== 7" type="primary"
          @click="scrollToBottomManually">
          {{ t('functionService.scroll_to_bottom_label') }}
        </div>
      </div>
      <div class="progress-bar p-t-10px" v-if="downloadConfig.export.isDownloading">
        <el-progress :text-inside="true" class="w-50%" :stroke-width="26" :percentage="downloadConfig.export.progress"
          striped striped-flow :duration="10" />
      </div>
    </div>
    <Mprogress 
      :show="downloadConfig.rssi.isDownloading"
      :progress="downloadConfig.rssi.progress"
      title="RSSI日志导出"
      progressText="正在下载日志文件"
      waitingText="请耐心等待，下载完成后将自动保存..."
      completeText="下载完成，即将保存文件..."
      primaryColor="#00d1ed"
      @close="handlePauseDownload('rssi')"
    />
    <Dialog
      v-bind="logLevelSettingDialog"
      v-model:dialogVisible="logLevelSettingDialog.dialogVisible"
    >
      <template #content>
      <div class="p-20px">
        <el-form
        :inline="true"
        >
        <el-form-item label="AP日志等级配置">
          <MSelect v-bind="logLevelSettingOptions" v-model="logLevelSettingDialog.logLevelSettingValue" />
        </el-form-item>
         <el-form-item>
          <div class="global_btn" style="width: 100px;" @click="handleLogLevelSetting">
            配置
          </div>
         </el-form-item>
      </el-form>
      </div>  
      </template>
    </Dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
  name: 'LogManageInfo',
})
</script>

<script setup lang="ts">
import { useI18n } from 'vue-i18n'
import { LogManageApi } from '@/api/logManage'
import { ElNotificationFn } from '@/utils/computedUtils'
import axios from 'axios'
import {getWebSocketInstance} from '@/utils/websocketExample'
import { throttle } from 'lodash'  // 需要安装 @types/lodash 依赖: npm install --save-dev @types/lodash
import { ArrowDown, Close, Delete } from '@element-plus/icons-vue'
import LogIndexedDB from '@/utils/LogIndexedDB'
import Mprogress from '@/components/Mprogress.vue'

// 添加类型定义
interface LogItem {
  content: string;
  index: number;
}
// 定义过滤配置类型
interface FilterConfig {
  filterValue: string;
  filterList: string[];
  unFilterList: string[];
}
// 下载配置类型
interface DownloadConfigItem {
  progress: number;
  cancelToken: any;
  isCancel: boolean;
  isDownloading: boolean;
}
interface DownloadConfig {
  rssi: DownloadConfigItem;
  export: DownloadConfigItem;
}
const props = defineProps({
    id: String,
    logTypeLabel: String,
    pageType:Number,
    isFirstLoad: {
      type: Boolean,
      default: true
    },
    fileName:String
})
const isExportLog = defineModel<boolean>('isExportLog', {
  required: true,
  default: false
})
const { t } = useI18n()
const itemHeight = 36 // 增加每项高度，留出间距
const bufferSize = 5 // 上下缓冲区大小
const visibleCount = 30 // 固定显示30条
// 单视图日志相关引用和状态
const containerRef = ref<HTMLElement | null>(null)
const scrollTop = ref(0) // 滚动条位置
const logList = ref<string[]>([]) // 日志列表
const contentLength = ref(0) //数据总条数
const totalHeight = computed(() => logList.value.length * itemHeight) // 计算总高度
const wsClient = getWebSocketInstance() // 获取websocket实例
const isUserScrolling = ref(false) // 判断用户是否正在主动滚动
const isAtBottom = ref(true) // 判断是否在底部
const newMessageCount = ref(0) // 新消息计数
const isInitialLoad = ref(true) // 是否是初始加载
const currentDataLength = defineModel<number>('currentDataLength', {
  required: true,
  default: 0
})
// 分屏视图日志相关引用和状态
const unfilteredContainerRef = ref<HTMLElement | null>(null)
const filteredContainerRef = ref<HTMLElement | null>(null)
const unfilteredScrollTop = ref(0)
const filteredScrollTop = ref(0)
const isUnfilteredUserScrolling = ref(false)
const isFilteredUserScrolling = ref(false)
const isUnfilteredAtBottom = ref(true)
const isFilteredAtBottom = ref(true)
const unfilteredNewMessageCount = ref(0)
const filteredNewMessageCount = ref(0)
// 未过滤日志视图计算属性
const unfilteredTotalHeight = computed(() => 
  cpFilterConfig.value.unFilterList.length * itemHeight
)
const getUnfilteredVisibleRange = () => {
  if (!unfilteredContainerRef.value) return { start: 0, end: 0 }
  const start = Math.floor(unfilteredScrollTop.value / itemHeight)
  return {
    start: Math.max(0, start - bufferSize),
    end: Math.min(
      cpFilterConfig.value.unFilterList.length, 
      start + visibleCount + bufferSize
    )
  }
}
const unfilteredOffsetY = computed(() => {
  const { start } = getUnfilteredVisibleRange()
  return start * itemHeight
})
const unfilteredVisibleData = computed((): LogItem[] => {
  if (cpFilterConfig.value.unFilterList.length === 0) return []
  const { start, end } = getUnfilteredVisibleRange()
  return cpFilterConfig.value.unFilterList.slice(start, end).map((content: string, index: number) => {
    const actualIndex = start + index
    return {
      content,
      index: actualIndex
    }
  })
})
// 过滤日志视图计算属性
const filteredTotalHeight = computed(() => 
  cpFilterConfig.value.filterList.length * itemHeight
)
const getFilteredVisibleRange = () => {
  if (!filteredContainerRef.value) return { start: 0, end: 0 }
  const start = Math.floor(filteredScrollTop.value / itemHeight)
  return {
    start: Math.max(0, start - bufferSize),
    end: Math.min(
      cpFilterConfig.value.filterList.length, 
      start + visibleCount + bufferSize
    )
  }
}
const filteredOffsetY = computed(() => {
  const { start } = getFilteredVisibleRange()
  return start * itemHeight
})
const filteredVisibleData = computed((): LogItem[] => {
  if (cpFilterConfig.value.filterList.length === 0) return []
  const { start, end } = getFilteredVisibleRange()
  return cpFilterConfig.value.filterList.slice(start, end).map((content: string, index: number) => {
    const actualIndex = start + index
    return {
      content,
      index: actualIndex
    }
  })
})
// 单视图滚动范围计算
const getVisibleRange = () => {  // 计算可见范围
  const start = Math.floor(scrollTop.value / itemHeight)
  return {
    start: Math.max(0, start - bufferSize),
    end: Math.min(logList.value.length, start + visibleCount + bufferSize)
  }
}
const offsetY = computed(() => { // 计算偏移量
  const { start } = getVisibleRange()
  return start * itemHeight
})
const visibleData = computed(() => {
  const { start, end } = getVisibleRange()
  return logList.value.slice(start, end).map((content, index) => {
    // 计算实际索引：当前切片的起始位置 + 在切片中的相对位置
    const actualIndex = start + index; 
    // 转换为从1开始的显示索引（和原来逻辑类似，但避免负数）
    return {
      content,
      index: actualIndex // 或者用Math.max(0, contentLength.value - (logList.value.length - actualIndex))
    };
  })
})
// 未过滤日志滚动处理
const throttledUnfilteredScrollHandler = throttle((e: Event) => {
  if (!unfilteredContainerRef.value) return
  const target = e.target as HTMLElement
  unfilteredScrollTop.value = target.scrollTop
  const isNearBottom = target.scrollHeight - target.scrollTop - target.clientHeight < 20
  isUnfilteredAtBottom.value = isNearBottom
  if (!isNearBottom) {
    isUnfilteredUserScrolling.value = true
  } else {
    isUnfilteredUserScrolling.value = false
    unfilteredNewMessageCount.value = 0
  }
}, 200)
const onUnfilteredScroll = (e: Event) => {
  throttledUnfilteredScrollHandler(e)
}
// 过滤日志滚动处理
const throttledFilteredScrollHandler = throttle((e: Event) => {
  if (!filteredContainerRef.value) return
  const target = e.target as HTMLElement
  filteredScrollTop.value = target.scrollTop
  const isNearBottom = target.scrollHeight - target.scrollTop - target.clientHeight < 20
  isFilteredAtBottom.value = isNearBottom
  
  if (!isNearBottom) {
    isFilteredUserScrolling.value = true
  } else {
    isFilteredUserScrolling.value = false
    filteredNewMessageCount.value = 0
  }
}, 200)
const onFilteredScroll = (e: Event) => {
  throttledFilteredScrollHandler(e)
}
// 未过滤日志滚动到底部
const scrollUnfilteredToBottom = async () => {
  if (unfilteredContainerRef.value) {
    await nextTick()
    const container = unfilteredContainerRef.value
    const scrollHeight = container.scrollHeight
    const clientHeight = container.clientHeight 
    if (isInitialLoad.value) {
      container.scrollTop = scrollHeight - clientHeight
    } else {
      container.scrollTo({
        top: scrollHeight - clientHeight,
        behavior: 'smooth'
      })
    }
  }
}
const scrollUnfilteredToBottomManually = () => {
  scrollUnfilteredToBottom()
  isUnfilteredUserScrolling.value = false
  isUnfilteredAtBottom.value = true
  unfilteredNewMessageCount.value = 0
}
// 过滤日志滚动到底部
const scrollFilteredToBottom = async () => {
  if (filteredContainerRef.value) {
    await nextTick()
    const container = filteredContainerRef.value
    const scrollHeight = container.scrollHeight
    const clientHeight = container.clientHeight
    if (isInitialLoad.value) {
      container.scrollTop = scrollHeight - clientHeight
    } else {
      container.scrollTo({
        top: scrollHeight - clientHeight,
        behavior: 'smooth'
      })
    }
  }
}
const scrollFilteredToBottomManually = () => {
  scrollFilteredToBottom()
  isFilteredUserScrolling.value = false
  isFilteredAtBottom.value = true
  filteredNewMessageCount.value = 0
}
// 下载配置
const downloadConfig = ref<DownloadConfig>({
  rssi: {
    progress: 0,
    cancelToken: null,
    isCancel: false,
    isDownloading: false
  },
  export: {
    progress: 0,
    cancelToken: null,
    isCancel: false,
    isDownloading: false
  }
})
// 日志过滤配置
const filterValue = ref('###')
const cpFilterConfig = ref<FilterConfig>({
  filterValue: '###',
  filterList:[],
  unFilterList:[]
})
function handleFilter(){
  cpFilterConfig.value.filterValue = filterValue.value
  handleFilterLog()
}
watch(()=>filterValue.value,(newVal)=>{
   if(newVal.trim() === ''){
    cpFilterConfig.value.filterValue = ''
    handleFilterLog()
   }
})
// 使用节流处理滚动事件，200ms内只处理一次
const throttledScrollHandler = throttle((e: Event) => {
  if (!containerRef.value) return
  const target = e.target as HTMLElement
  scrollTop.value = target.scrollTop
  const isNearBottom = target.scrollHeight - target.scrollTop - target.clientHeight < 20
  isAtBottom.value = isNearBottom
  if (!isNearBottom) {
    isUserScrolling.value = true
  } else {
    isUserScrolling.value = false
    // 如果滚动到底部，重置新消息计数
    newMessageCount.value = 0
  }
}, 200)
const onScroll = (e: Event) => {
  throttledScrollHandler(e)
}
// 添加新日志到列表末尾
const appendNewLog = (logMessage: string) => {
  logList.value.push(...logMessage.split('\n').filter(item=>item.trim() !== ''))
  contentLength.value = logList.value.length
  currentDataLength.value = logList.value.length
  // 如果用户没有主动滚动（即在底部），则自动滚动到底部
  if (!isUserScrolling.value || isAtBottom.value) {
    nextTick(() => {
      scrollToBottom()
    })
  } else {
    newMessageCount.value++
  }
}
// 分屏模式下添加日志
function appendFilterNewLog(logMessage: string) {
  const logList = logMessage.split('\n').filter(item=>item.trim() !== '')
  logList.forEach(item => {
    if (item.includes(cpFilterConfig.value.filterValue)) {
      cpFilterConfig.value.filterList.push(item)    
      // 更新过滤日志滚动位置
      if (!isFilteredUserScrolling.value || isFilteredAtBottom.value) {
        nextTick(() => {
          scrollFilteredToBottom()
        })
      } else {
        filteredNewMessageCount.value++
      }
    }
    cpFilterConfig.value.unFilterList.push(item)
      // 更新未过滤日志滚动位置
      if (!isUnfilteredUserScrolling.value || isUnfilteredAtBottom.value) {
        nextTick(() => {
          scrollUnfilteredToBottom()
        })
      } else {
        unfilteredNewMessageCount.value++
      }
  }) 
  // 更新当前总数据长度
  currentDataLength.value = cpFilterConfig.value.unFilterList.length + cpFilterConfig.value.filterList.length
}
// 处理过滤操作
const handleFilterLog = () => {
  // 清空之前的过滤结果
  cpFilterConfig.value.filterList = []
  // 对现有日志进行过滤
  cpFilterConfig.value.unFilterList.forEach((item: string) => {
    if (item.includes(cpFilterConfig.value.filterValue)) {
      cpFilterConfig.value.filterList.push(item)
    }
  })
  // 更新滚动位置
  nextTick(() => {
    scrollUnfilteredToBottom()
    scrollFilteredToBottom()
  })
}
// 通过WebSocket获取完整日志
async function getFullLog(){
    const response = await LogManageApi.reqDownloadLog({ 
      type:props.pageType
    })
    const downloadUrl = response.data.addr
    const {data} = await axios({
      url: downloadUrl,
    })
    // 根据pageType的不同，处理日志的方式也不同
    if (props.pageType === 7) {
      // 分屏模式下，需要分别处理过滤和未过滤的日志
      const logs = data.split('\n').filter(item => item.trim() !== '')
      // 清空原有数据
      cpFilterConfig.value.unFilterList = []
      cpFilterConfig.value.filterList = []
      // 按过滤条件分类日志
      logs.forEach((item: string) => {
        if (item.includes(cpFilterConfig.value.filterValue)) {
          cpFilterConfig.value.filterList.push(item)
        } else {
          cpFilterConfig.value.unFilterList.push(item)
        }
      })
      
      currentDataLength.value = logs.length
    } else {
      // 正常模式
      contentLength.value = data.split('\n').length
      logList.value = data.split('\n')
      currentDataLength.value = logList.value.length
    }  
    await LogManageApi.reqGetFullLog({type:props.pageType})
    await nextTick()    
    // 根据pageType的不同，处理滚动的方式也不同
    if (props.pageType === 7) {
      scrollUnfilteredToBottom()
      scrollFilteredToBottom()
    } else {
      scrollToBottom()
    }
    
    isInitialLoad.value = false
    if (props.isFirstLoad) {
      wsClient.send({command :'log-start',data:{type:props.pageType}})
    }
} 
const scrollToBottom = async () => {
  if (containerRef.value) {
    await nextTick()
    const container = containerRef.value
    const scrollHeight = container.scrollHeight
    const clientHeight = container.clientHeight
    
    if(isInitialLoad.value){
      container.scrollTop = scrollHeight - clientHeight
    }else{
      container.scrollTo({
        top: scrollHeight - clientHeight,
        behavior: 'smooth'
      })
    }
  }
}
const scrollToBottomManually = () => {
  scrollToBottom()
  isUserScrolling.value = false
  isAtBottom.value = true
  newMessageCount.value = 0
}
// 在组件中添加对WebSocket消息的监听
const setupWebSocketListener = () => {
  wsClient.on('message', (response: any) => {
    const { data, cmd } = response
    if (cmd !== 'log_get') return
    if (data.type === props.pageType) {
      if(props.pageType === 7){
        appendFilterNewLog(data.msg)
      }else{
        appendNewLog(data.msg)
      }
    }
  })
}
async function downloadFile(type: 'rssi' | 'export') {
  const config = downloadConfig.value[type];
  const typeName = type === 'rssi' ? 'RSSI日志' : props.logTypeLabel;
  try {
    const response = await LogManageApi.reqDownloadLog({ 
      id: type === 'rssi' ? 6 : props.pageType
    });
    const downloadUrl = response.data.addr;
    const id = response.data.id;   
    config.isDownloading = true;
    config.isCancel = false;
    config.progress = 0;
    config.cancelToken = axios.CancelToken.source(); 
    // 添加下载开始的通知
    if (type === 'rssi') {
      ElNotificationFn('info', 'RSSI日志导出已开始');
    }
    const res = await axios({
      url: downloadUrl,
      responseType: 'blob',
      onDownloadProgress: (progressEvent: any) => {
        if (progressEvent.total) {
          // 平滑的进度更新
          const newProgress = Math.round((progressEvent.loaded / progressEvent.total) * 100);
          // 使用动画平滑过渡进度
          const updateProgress = () => {
            const currentProgress = config.progress;
            if (currentProgress < newProgress) {
              config.progress = Math.min(currentProgress + 1, newProgress);
              if (config.progress < newProgress) {
                requestAnimationFrame(updateProgress);
              }
            }
          };
          updateProgress();
        }
      },
      cancelToken: config.cancelToken.token
    });   
    // 确保进度到达100%
    config.progress = 100;
    const blob = new Blob([res.data], { type: 'text/plain' });
    const a = document.createElement('a');
    const timePrefix = setNowTime()
    a.href = window.URL.createObjectURL(blob);
    a.download = type === 'rssi' ? `cscn_device_rssi_log-${timePrefix}.dump` : `${props.fileName}-${timePrefix}.log`
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(a.href);   
    ElNotificationFn('success', `${typeName}下载完成`);
    // 延迟关闭进度面板，给用户查看完成状态的时间
    if (type === 'rssi') {
      // 返回一个Promise，在进度面板关闭后resolve
      return new Promise<void>((resolve) => {
        setTimeout(() => {
          config.isDownloading = false;
          resolve();
        }, 1800);
      });
    }
  } catch (error: any) {
    if (config.isCancel) {
      ElNotificationFn('warning', `${typeName}下载已取消`);
      return;
    }
    ElNotificationFn('error', t('functionService.download_file_failure_label'));
    throw error; // 重新抛出错误捕获
  } finally {
    if (type !== 'rssi' || config.isCancel) {
      config.isDownloading = false;
    }
  }
}
async function handleDownloadLog() {
   await downloadFile('export')
}
function handleCurrentExportLog(){  
    const blod = new Blob([logList.value.join('\n')], { type: 'text/plain' });
    const a = document.createElement('a');
    const timePrefix = setNowTime()
    a.href = window.URL.createObjectURL(blod);
    a.download = `${props.id}(${timePrefix}).log`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(a.href);
}
function clearCplog(type: 'filtered' | 'unfiltered'){
  if(type === 'filtered'){
    cpFilterConfig.value.filterList = []
  }else{
    cpFilterConfig.value.unFilterList = []
  }
}
function setNowTime(){
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}-${minutes}-${seconds}`
}
function handleExportCpLog(type: 'filtered' | 'unfiltered'){
  const allLogs = type === 'unfiltered' ? cpFilterConfig.value.unFilterList : cpFilterConfig.value.filterList
  const blod = new Blob([allLogs.join('\n')], { type: 'text/plain' });
  const a = document.createElement('a');
  const timePrefix = setNowTime()
  a.href = window.URL.createObjectURL(blod);
  a.download = type === 'unfiltered' ? `${props.fileName}-${timePrefix}.log` : `cscn_device_cp_access_log-${timePrefix}.log`
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  window.URL.revokeObjectURL(a.href);
}
async function handleExportLog() {
  // 确保开始下载前结束之前的下载
  if (downloadConfig.value.rssi.isDownloading) {
    handlePauseDownload('rssi');
  } 
  // 直接返回下载操作的Promise
  return new Promise<void>(async (resolve, reject) => {
    try {
      await downloadFile('rssi');
      resolve();
    } catch (error) {
      console.error('RSSI日志导出失败:', error);
      reject(error);
    }
  });
}
const handlePauseDownload = (type: 'rssi' | 'export') => {
  const config = downloadConfig.value[type]
  config.cancelToken?.cancel()
  config.isCancel = true
  config.isDownloading = false
  config.cancelToken = null
  config.progress = 0
}
watch(()=>isExportLog.value,async ()=>{
  if(isExportLog.value){
    try {
      await handleExportLog()
    } finally {
      // 等待一段时间后再设置回false，确保父组件有足够时间显示loading状态
      setTimeout(() => {
        isExportLog.value = false
      }, 500)
    }
  }
})
const loadInitialData = async () => {
  const logDB = LogIndexedDB.getInstance()
  await logDB.init()
  // 从IndexedDB加载指定类型的日志
  const logs = await logDB.getLogsByType(props.pageType as number)
  if (props.pageType === 7) {
    // 分屏模式，需要分别处理过滤和未过滤的日志
    const allMessages = logs.map(log => log.message.split('\n').filter((item: string) => item.trim() !== '')).flat()
    // 按过滤条件分类日志
    allMessages.forEach((item: string) => {
      if (item.includes(cpFilterConfig.value.filterValue)) {
        cpFilterConfig.value.filterList.push(item)
      }
      cpFilterConfig.value.unFilterList.push(item)
    })
    currentDataLength.value = allMessages.length
    await nextTick()
    scrollUnfilteredToBottom()
    scrollFilteredToBottom()
  } else {
    // 正常模式
    logList.value = logs.map(log => log.message.split('\n').filter(item=>item.trim() !== '')).flat() 
    contentLength.value = logList.value.length
    currentDataLength.value = logList.value.length
    
    await nextTick()
    scrollToBottom()
  }
}
function handleClearLog(){
  if(props.pageType === 7){
    // 分屏模式
    cpFilterConfig.value.unFilterList = []
    cpFilterConfig.value.filterList = []
  } else {
    // 正常模式
    logList.value = []
    contentLength.value = 0
  }
  currentDataLength.value = 0
}
const logLevelSettingDialog = ref({
  title: '日志等级设置',
  width: '500',
  dialogVisible: false,
  logLevelSettingValue: "",
})
const logLevelSettingOptions = ref({
  options:[
    {
      label: '输出所有日志',
      value: 0, // LOG_LEVEL_NOTSET
    },
    {
      label: '跟踪',
      value: 1, // LOG_LEVEL_TRACE
    },
    {
      label: '调试',
      value: 2, // LOG_LEVEL_DEBUG
    },
    {
      label: '信息',
      value: 3, // LOG_LEVEL_INFO
    },
    {
      label: '警告',
      value: 4, // LOG_LEVEL_WARN
    },
    {
      label: '错误',
      value: 5, // LOG_LEVEL_ERROR
    },
    {
      label: '不输出任何日志',
      value: 6, // LOG_LEVEL_NONE
    }
  ],
  placeholder: '选择日志等级',
  width: '200px'
})
async function showLogLevelSettingDialog(){
   logLevelSettingDialog.value.dialogVisible = true
}
async function handleLogLevelSetting(){
  await LogManageApi.reqLogLevelSetting({
    level: logLevelSettingDialog.value.logLevelSettingValue
  })
  ElNotificationFn('success', '日志等级设置成功')
  logLevelSettingDialog.value.dialogVisible = false
  getLogLevel()
}

const currentLogLevel = ref('')
async function getLogLevel(){
   const res = await LogManageApi.reqLogLevelGet()
  currentLogLevel.value = logLevelSettingOptions.value.options.find(item=>item.value == res.data.level)?.label || '输出所有日志'
}
onMounted(async () => {
  getLogLevel()
  await loadInitialData()
  setupWebSocketListener()
})

onActivated(async () => {
  if (props.pageType === 7) {
    // 分屏模式
    if (unfilteredContainerRef.value) {
      unfilteredContainerRef.value.scrollTop = unfilteredScrollTop.value
    }
    if (filteredContainerRef.value) {
      filteredContainerRef.value.scrollTop = filteredScrollTop.value
    }
  } else {
    // 正常模式
    if (containerRef.value) {
      containerRef.value.scrollTop = scrollTop.value
    }
  }
})

onBeforeUnmount(() => {
  throttledScrollHandler.cancel()
  throttledUnfilteredScrollHandler.cancel()
  throttledFilteredScrollHandler.cancel()
})
</script>

<style lang="scss" scoped>
@import '@/styles/progress.scss';
@import '@/styles/input.scss';
@import '@/styles/form.scss';
.log-manage-info {
  display: flex;
  flex-direction: column;
  height: 130%;
  overflow: hidden;
  padding: 0 10px;
 
  // 淡入淡出动画效果
  .fade-enter-active,
  .fade-leave-active {
    transition: opacity 0.3s ease, transform 0.3s ease;
  }
  .fade-enter-from,
  .fade-leave-to {
    opacity: 0;
    transform: translateY(10px);
  }
  
  // 分屏日志包装容器
  .split-log-wrapper {
    position: relative;
    margin-bottom: 20px; // 增加底部外边距，为按钮和控制面板预留空间
  }

  // 分屏日志容器
  .split-log-container {
    display: flex;
    justify-content: space-between;
    height: 500px; // 固定高度
    gap: 20px;
  }

  // 日志面板通用样式
  .log-panel {
    flex: 1;
    min-width: 45%;
    display: flex;
    flex-direction: column;
    position: relative;
    border: 1px solid rgba(31, 106, 178, 0.3);
    border-radius: 4px;
    background: rgba(0, 17, 45, 0.3);
    overflow: hidden;
    height: 100%;
    max-height: 100%;

    .panel-title {
      padding: 10px 15px;
      font-size: 16px;
      font-weight: 500;
      color: #00d1ed;
      background: rgba(0, 17, 45, 0.7);
      border-bottom: 1px solid rgba(31, 106, 178, 0.3);
      text-shadow: 0 0 10px rgba(0, 209, 237, 0.5);
      flex-shrink: 0; // 防止标题被压缩
      
      .filter-count {
        color: #ffaa00;
        font-size: 14px;
        margin-left: 8px;
      }
    }
  }

  // 未过滤日志特有样式
  .unfiltered-logs {
    border-left: 3px solid rgba(0, 209, 237, 0.5);
  }

  // 过滤日志特有样式
  .filtered-logs {
    border-left: 3px solid rgba(255, 170, 0, 0.5);
    
    .panel-title {
      color: #ffaa00;
      text-shadow: 0 0 10px rgba(255, 170, 0, 0.5);
    }
  }

  // 底部按钮容器
  .scroll-buttons-container {
    position: absolute;
    bottom: -60px;
    left: 0;
    right: 0;
    height: 50px;
    z-index: 500;
    display: flex;
    // justify-content: space-between;
    pointer-events: none; // 允许点击穿透到下方元素
    .global_btn {
      pointer-events: auto; // 恢复按钮的点击功能
    }
  }
  
  .unfiltered-scroll-btn {
    margin-left: 20px;
    position: absolute;
    left: 0;
  }
  
  .filtered-scroll-btn {
    margin-right: 20px;
    position: absolute;
    right: 0;
  }

  // 没有结果的提示
  .no-results {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: rgba(255, 255, 255, 0.5);
    font-size: 14px;
    text-align: center;
  }

  // 单视图日志容器样式
  .log_container {
    flex: 1;
    position: relative;
    background: rgba(0, 17, 45, 0.5);
    overflow: auto;
    padding: 10px;
    border: 1px solid rgba(31, 106, 178, 0.3);
    border-radius: 4px;
    max-height: calc(100% - 40px); // 减去标题高度
    min-height: 0; // 允许容器收缩

    &::-webkit-scrollbar {
      width: 8px;
      height: 8px;
    }

    &::-webkit-scrollbar-thumb {
      background: rgba(255, 255, 255, 0.2);
      border-radius: 4px;
      
      &:hover {
        background: rgba(255, 255, 255, 0.3);
      }
    }

    &::-webkit-scrollbar-track {
      background: transparent;
    }
  }

  .control-panel {
    min-height: 60px; // 为底部控制面板预留空间
    margin-top: 10px; // 增加与日志区域的间距
    background: rgba(0, 17, 45, 0.3); // 添加背景色
    border-radius: 4px; // 添加圆角
    padding: 15px; // 添加内边距
    padding-bottom: 0;
    height: 100px;
    // border: 1px solid rgba(31, 106, 178, 0.3); // 添加边框
  }

  .virtual-list {
    position: relative;
    width: 100%;
  }

  .virtual-list-phantom {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    z-index: 0;
    min-width: 100%;
  }

  .log-item {
    padding: 6px 20px;
    margin-top: 4px;
    line-height: 20px;
    margin-bottom: 0;
    height: 32px;
    box-sizing: border-box;
    white-space: nowrap;
    min-width: 100%;
    color: #fff;
    border-radius: 4px;
    transition: background-color 0.2s; // 修改这行
    &:hover {
      background-color: rgba(255, 255, 255, 0.1);
    }

    .log-index {
      display: inline-block;
      min-width: 50px;
      margin-right: 8px;
      color: #384b5e;
      font-family: monospace;
      font-size: 12px;
    }

    .log-content {
      font-size: 16px;
      color: rgba(255, 255, 255, 0.9);
    }
  }

  .log-level-text {
    font-weight: bold;
    color: #00d1ed;
    padding: 2px 8px;
    border-radius: 4px;
    background-color: rgba(0, 209, 237, 0.1);
  }
}
</style>
